package com.china08.yxyapi.api.home.activity.healthcompetition;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.huodong.healthcompetition.YxyCompetitionStudent;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.huodong.YxyCompetitionStudentRepository;
import com.china08.yxyapi.security.profile.YxyProfile;

/**
 * 判断当前用户是否有参与知识竞赛答题资格
 * 
 * @author zd.Jin
 *
 *
 */
@RestController
@CrossOrigin
public class JudgeUserInfoController extends YxyApiBaseController {
	private static Logger LOGGER = LoggerFactory.getLogger(JudgeUserInfoController.class);
	@Value("${yx.rest.api.yx.path}")
	private String yxpath;
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private YxyCompetitionStudentRepository yxyCompetitionStudentRepository;

	@RequestMapping(value = "/api_yw/home/activity/healthcompetition/user/judge", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public RespModel process(HttpServletRequest request, HttpServletResponse response) {
		RespModel respModel = new RespModel();
		// 得到当前登录用户
		YxyProfile profile = getProfile(request, response);
		String userId = profile.getId();
		String roleName = profile.getRoleId();
		// 当前用户是学生时
		if ("ROLE_STUDENT".equals(roleName) && "230100".equals(profile.getSchoolAreaIdCity())) {
			try {
				HttpHeaders headers = new HttpHeaders();
				MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
				headers.setContentType(type);
				headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
				Map<String, Object> formMap = new HashMap<String, Object>();
				formMap.put("studentId", userId);
				HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
				StudentInfo httpResult = restTemplate.postForObject(yxpath + "/comm/stu/stuinfobystuid", formEntity,
						StudentInfo.class);
				String stage = httpResult.phaseId;
				Integer schStatus = httpResult.schStatus;
				Integer classStatus = httpResult.classStatus;
				String stuStatus = httpResult.stuStatus;
				// 当前学生学段是小学初中高中时
				if ("SS1".equals(stuStatus) && schStatus == 1 && classStatus == 0
						&& ("1".equals(stage) || "2".equals(stage) || "3".equals(stage))) {
					respModel.notice = "true";
					// 查询参与作答学生是否存在,不存在添加,存在更新
					YxyCompetitionStudent yxyCompetitionStudent = yxyCompetitionStudentRepository
							.findTop1ByStudentId(userId);
					if (yxyCompetitionStudent == null) {
						yxyCompetitionStudent = new YxyCompetitionStudent();
						yxyCompetitionStudent.setStatus(0);
						yxyCompetitionStudent.setScore(0);
						yxyCompetitionStudent.setPaperNum("");// 试卷编号根据学段判断
					}
					yxyCompetitionStudent.setImg(httpResult.img == null ? "" : httpResult.img);
					yxyCompetitionStudent.setStage(httpResult.phasename == null ? "" : httpResult.phasename);
					yxyCompetitionStudent.setGrade(httpResult.grade == null ? "" : httpResult.grade);
					yxyCompetitionStudent.setStudentId(userId);
					yxyCompetitionStudent.setStudentNick(profile.getUserNick() == null ? "" : profile.getUserNick());
					yxyCompetitionStudent.setClassId(httpResult.classId == null ? "" : httpResult.classId);
					yxyCompetitionStudent.setClassName(httpResult.classname == null ? "" : httpResult.classname);
					yxyCompetitionStudent.setAreaCodeProvince(
							profile.getSchoolAreaIdProvince() == null ? "" : profile.getSchoolAreaIdProvince());
					yxyCompetitionStudent
							.setAreaNameProvince(httpResult.provinceName == null ? "" : httpResult.provinceName);
					yxyCompetitionStudent.setAreaCodeCity(
							profile.getSchoolAreaIdCity() == null ? "" : profile.getSchoolAreaIdCity());
					yxyCompetitionStudent.setAreaNameCity(httpResult.cityName == null ? "" : httpResult.cityName);
					yxyCompetitionStudent
							.setAreaNameDistrict(httpResult.districtName == null ? "" : httpResult.districtName);
					yxyCompetitionStudent.setAreaCodeDistrict(
							profile.getSchoolAreaIdDistrict() == null ? "" : profile.getSchoolAreaIdDistrict());
					yxyCompetitionStudent.setSchoolId(profile.getSchoolId() == null ? "" : profile.getSchoolId());
					yxyCompetitionStudent.setSchoolName(profile.getSchoolName() == null ? "" : profile.getSchoolName());
					yxyCompetitionStudentRepository.save(yxyCompetitionStudent);
				} else {
					respModel.notice = "false";
				}
			} catch (Exception e) {
				respModel.notice = "获取学生学段接口链接失败";
				e.printStackTrace();
			}
		}
		// 当前用户是家长时
		else if ("ROLE_PARENTS".equals(roleName)) {
			try {
				HttpHeaders headers = new HttpHeaders();
				MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
				headers.setContentType(type);
				headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
				Map<String, Object> formMap = new HashMap<String, Object>();
				formMap.put("parentId", userId);
				HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
				ParRespModel httpResult = restTemplate.postForObject(yxpath + "/comm/par/selectyoungchild", formEntity,
						ParRespModel.class);
				List<StudentInfo> students = httpResult.studentInfos;
				if (students != null && students.size() > 0) {
					respModel.notice = "true";
					for (StudentInfo studentInfo : students) {
						// 查询参与作答学生是否存在,不存在添加,存在更新
						YxyCompetitionStudent yxyCompetitionStudent = yxyCompetitionStudentRepository
								.findTop1ByStudentId(studentInfo.studentId);
						if (yxyCompetitionStudent == null) {
							yxyCompetitionStudent = new YxyCompetitionStudent();
							yxyCompetitionStudent.setStatus(0);
							yxyCompetitionStudent.setScore(0);
							yxyCompetitionStudent.setPaperNum("");// 试卷编号根据学段判断
						}
						yxyCompetitionStudent.setImg(studentInfo.img == null ? "" : studentInfo.img);
						yxyCompetitionStudent.setStage(studentInfo.phasename == null ? "" : studentInfo.phasename);
						yxyCompetitionStudent.setGrade(studentInfo.grade == null ? "" : studentInfo.grade);
						yxyCompetitionStudent.setStudentId(studentInfo.studentId == null ? "" : studentInfo.studentId);
						yxyCompetitionStudent
								.setStudentNick(studentInfo.studentname == null ? "" : studentInfo.studentname);
						yxyCompetitionStudent.setClassId(studentInfo.classId == null ? "" : studentInfo.classId);
						yxyCompetitionStudent.setClassName(studentInfo.classname == null ? "" : studentInfo.classname);
						yxyCompetitionStudent
								.setAreaCodeProvince(studentInfo.provinceId == null ? "" : studentInfo.provinceId);
						yxyCompetitionStudent
								.setAreaNameProvince(studentInfo.provinceName == null ? "" : studentInfo.provinceName);
						yxyCompetitionStudent.setAreaCodeCity(studentInfo.cityId == null ? "" : studentInfo.cityId);
						yxyCompetitionStudent.setAreaNameCity(studentInfo.cityName == null ? "" : studentInfo.cityName);
						yxyCompetitionStudent
								.setAreaCodeDistrict(studentInfo.districtId == null ? "" : studentInfo.districtId);
						yxyCompetitionStudent
								.setAreaNameDistrict(studentInfo.districtName == null ? "" : studentInfo.districtName);
						yxyCompetitionStudent.setSchoolId(studentInfo.schoolId == null ? "" : studentInfo.schoolId);
						yxyCompetitionStudent
								.setSchoolName(studentInfo.schoolname == null ? "" : studentInfo.schoolname);
						yxyCompetitionStudentRepository.save(yxyCompetitionStudent);
						LOGGER.info("student*********************" + yxyCompetitionStudent.getStudentNick()
								+ "******city" + yxyCompetitionStudent.getAreaCodeCity());
					}
				} else {
					respModel.notice = "false";
				}
			} catch (Exception e) {
				respModel.notice = "获取学生列表接口链接失败";
				e.printStackTrace();
			}
		}
		// 当前用户是其它身份
		else {
			respModel.notice = "false";
		}
		return respModel;
	}

	protected static class RespModel extends YxyApiRespModel {
		public String notice;// true表示有参与资格,false表示没有参与资格,其它代表报错
	}

	// 家长身份远程调用接口返回类型
	protected static class ParRespModel {
		public List<StudentInfo> studentInfos;
	}

	// 学生身份远程调用接口返回类型
	protected static class StudentInfo {
		// 学生id
		public String studentId;
		// 头像
		public String img;
		// 学生名称
		public String studentname;
		// 学段
		public String phaseId;
		// 学段名称
		public String phasename;
		// 年级
		public String grade;
		// 班级id
		public String classId;
		// 班级名称
		public String classname;
		// 学校id
		public String schoolId;
		// 学校名称
		public String schoolname;
		// 省名称
		public String provinceName;
		// 市名称
		public String cityName;
		// 县名称
		public String districtName;
		// 省id
		public String provinceId;
		// 市id
		public String cityId;
		// 县id
		public String districtId;
		// 学校状态
		public Integer schStatus;
		// 班级状态
		public Integer classStatus;
		// 学生状态
		public String stuStatus;
	}
}
